import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newHttpClient();
        int skip = 0;
        // 每次最多查询100条
        int limit = 100;
        // 题目总数
        int count = 0;
        int coreThread = 5;
        ExecutorService executorService = Executors.newFixedThreadPool(coreThread);
        while (true) {
            String problemRequestBody = """
                    {
                        "query": "\\n    query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {\\n  problemsetQuestionList(\\n    categorySlug: $categorySlug\\n    limit: $limit\\n    skip: $skip\\n    filters: $filters\\n  ) {\\n    hasMore\\n    total\\n    questions {\\n  titleSlug\\n }\\n  }\\n}\\n    ",
                        "variables": {
                            "categorySlug": "all-code-essentials",
                            "skip": %d,
                            "limit": %d,
                            "filters": {}
                        },
                        "operationName": "problemsetQuestionList"
                    }
                    """.formatted(skip, limit);
            HttpRequest problemsRequest = HttpRequest.newBuilder()
                    .uri(URI.create("https://leetcode.cn/graphql/"))
                    .header("Content-Type", "application/json") // 添加此行
                    .POST(HttpRequest.BodyPublishers.ofString(problemRequestBody))
                    .build();
            HttpResponse<String> problemsResponse = httpClient.send(problemsRequest, responseInfo -> HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8));

            JSONObject problemObject = JSON.parseObject(problemsResponse.body(), JSONObject.class);
            JSONObject problemData = problemObject.getJSONObject("data");
            JSONObject problemsetQuestionList = problemData.getJSONObject("problemsetQuestionList");

            Boolean hasMore = problemsetQuestionList.getBoolean("hasMore");
            JSONArray questions = problemsetQuestionList.getJSONArray("questions");

            CountDownLatch countDownLatch = new CountDownLatch(questions.size());
            for (int i = 0; i < questions.size(); i++) {
                JSONObject questionObject = questions.getJSONObject(i);
                String finalTitleSlug = questionObject.getString("titleSlug");
                executorService.submit(() -> {
                    // 明细查询
                    String detialRequestBody = """
                            {
                              "operationName": "getQuestionDetail",
                              "variables": { "titleSlug": \"%s\" },
                              "query": "query getQuestionDetail($titleSlug: String!) {\\n  question(titleSlug: $titleSlug) {\\n    questionId\\n    title\\n translatedTitle\\n   content\\n translatedContent\\n   codeSnippets {\\n      lang\\n      code\\n    }\\n    sampleTestCase\\n    exampleTestcases\\n    metaData\\n difficulty\\n  }\\n}"
                            }
                            """.formatted(finalTitleSlug);
                    HttpRequest detailRequest = HttpRequest.newBuilder()
                            .uri(URI.create("https://leetcode.cn/graphql/"))
                            .header("Content-Type", "application/json") // 添加此行
                            .POST(HttpRequest.BodyPublishers.ofString(detialRequestBody))
                            .build();
                    try {
                        HttpResponse<String> detailResponse = httpClient.send(detailRequest, responseInfo -> HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8));

                        JSONObject detailObject = JSON.parseObject(detailResponse.body(), JSONObject.class);
                        JSONObject detailData = detailObject.getJSONObject("data");

                        // =================== 题目明细 =================================
                        JSONObject questionDetail = detailData.getJSONObject("question");
                        System.out.println(questionDetail);
                        // ===================================================

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    countDownLatch.countDown();
                });
            }
            countDownLatch.await();

            count += questions.size();
            if (!hasMore) {
                System.out.println("题目总数：" + count);
                break;
            }
            skip += limit;
        }

        executorService.shutdownNow();
    }
}
